package com.app.framework.socket.codec;

import java.util.List;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.app.framework.socket.Packet;

public class PacketEncoder extends OneToOneEncoder {
	
	private final static Logger logger = Logger.getLogger(PacketEncoder.class);
	// 消息长度较大的报警信息
	private final static int LENGTH_WARN = 2048;
	
	@SuppressWarnings("unchecked")
	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel,
			Object msg) throws Exception {
		
		ChannelBuffer[] cbs;
		
		if (msg instanceof Object[]) {

			Object[] objs = (Object[]) msg;
			
			cbs = new ChannelBuffer[objs.length];
			
			for (int i=0;i<objs.length;i++) {
				
				cbs[i] = encode((Packet)objs[i]);
            }
        } else if (msg instanceof List<?>) {
        	
        	List<Packet> pks = (List<Packet>)msg;
        	
        	cbs = new ChannelBuffer[pks.size()];
        	
        	for (int i=0;i<pks.size();i++) {
        		
				cbs[i] = encode((Packet)pks.get(i));
            }
        } else {
        	
        	return encode((Packet)msg);
        }
		
		return ChannelBuffers.wrappedBuffer(cbs);
	}

	private ChannelBuffer encode(Packet packet) {
		
		short length = (short) packet.getContent().length;
		
		int total = 4 + length;
		
		ChannelBuffer cb = ChannelBuffers.buffer(total);
		
		cb.writeShort(length);//消息体长度
		
		cb.writeShort(packet.getType());
		
		cb.writeBytes(packet.getContent());
		
		if(length > LENGTH_WARN) {
			logger.warn("packet ["+packet.getType() + "] [encodeMsgTooBig] [" + length + "]");
		}
		
		return cb;
	}
	
}
